package com.example.controller;

import com.example.entity.WeightRecord;
import com.example.service.WeightRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
@RequestMapping("/weightrecord")
public class WeightRecordController {

    @Autowired
    private WeightRecordService weightRecordService;

    @GetMapping("/list")
    public String list(Model model) {
        List<WeightRecord> records = weightRecordService.getAllWeightRecords();
        model.addAttribute("weightrecord", records);
        return "weightrecord/list";
    }

    @GetMapping("/add")
    public String toAddPage() {
        return "weightrecord/add";
    }

    @PostMapping("/add")
    public String add(WeightRecord record, RedirectAttributes redirectAttributes) {
        int result = weightRecordService.addWeightRecord(record);
        if (result > 0) {
            redirectAttributes.addFlashAttribute("success", "记录添加成功");
        } else {
            redirectAttributes.addFlashAttribute("error", "记录添加失败");
        }
        return "redirect:/weightrecord/list";
    }

    @GetMapping("/edit/{id}")
    public String toEditPage(@PathVariable("id") Integer id, Model model) {
        WeightRecord record = weightRecordService.getWeightRecordById(id);
        model.addAttribute("record", record);
        return "weightrecord/edit";
    }

    @PostMapping("/edit")
    public String edit(WeightRecord record, RedirectAttributes redirectAttributes) {
        int result = weightRecordService.updateWeightRecord(record);
        if (result > 0) {
            redirectAttributes.addFlashAttribute("success", "记录更新成功");
        } else {
            redirectAttributes.addFlashAttribute("error", "记录更新失败");
        }
        return "redirect:/weightrecord/list";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") Integer id, RedirectAttributes redirectAttributes) {
        int result = weightRecordService.deleteWeightRecord(id);
        if (result > 0) {
            redirectAttributes.addFlashAttribute("success", "记录删除成功");
        } else {
            redirectAttributes.addFlashAttribute("error", "记录删除失败");
        }
        return "redirect:/weightrecord/list";
    }
}